package org.example.versi.server;

import lombok.extern.slf4j.Slf4j;
import org.example.common.RpcRequest;
import org.example.common.RpcResponse;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;

/**
 * @author mojito
 * @Classname RpcHandler
 * @Description TODO
 * @Date 2020/7/20 下午9:26
 **/
@Slf4j
public class RpcHandler implements Runnable {
    private Socket socket;
    private Map<String, Object> serviceMap;

    public RpcHandler(Socket socket, Map<String, Object> serviceMap) {
        this.socket = socket;
        this.serviceMap = serviceMap;
    }

    @Override
    public void run() {
        ObjectInputStream inputStream = null;
        ObjectOutputStream outputStream = null;
        try {
            inputStream = new ObjectInputStream(socket.getInputStream());
            RpcRequest request = (RpcRequest) inputStream.readObject();
            log.info("rpc call com in:[{}]", request);
            Class<?> target = Class.forName(request.getClassName());
            Method method = target.getMethod(request.getMethodName(), request.getParameterTypes());
            RpcResponse invoke = (RpcResponse) method.invoke(serviceMap.get(request.getClassName()), request.getParams());
            invoke.setRequestId(request.getRequestId());
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(invoke);
            outputStream.flush();
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            try {
                socket.close();
                inputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
